//
//  UIImage+Tool.m
//  02-图片裁剪
//
//  Created by apple on 14-9-4.
//  Copyright (c) 2014年 itcast. All rights reserved.
//

#import "UIImage+Tool.h"

@implementation UIImage (Tool)

+ (instancetype)imageWithName:(NSString *)name border:(CGFloat)border borderColor:(UIColor *)color
{
//0、计算尺寸
    //圆环的宽度
    CGFloat borderW = 5;
    // 加载旧的图片
    UIImage *oldImage =  [UIImage imageNamed:name];
    // 新的图片尺寸
    CGFloat imageW = oldImage.size.width + 2 * borderW;
    CGFloat imageH = oldImage.size.height + 2 * borderW;
    // 设置新的图片尺寸
    CGFloat circirW = imageW > imageH ? imageH : imageW;
    
//1、开启图片上下文（circirW宽高内操作图片）
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(circirW, circirW), NO, 0.0);
    
//2、画大圆
    UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, circirW, circirW)];
    
//3、获取当前上下文
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
//4、将路径添加到上下文，设置填充颜色并且进行渲染
    CGContextAddPath(ctx, path.CGPath);
    [color set];
    CGContextFillPath(ctx);
    
//5、设置图片的剪切区域
    CGRect clipR = CGRectMake(borderW, borderW, oldImage.size.width, oldImage.size.height);
    UIBezierPath *clipPath = [UIBezierPath bezierPathWithOvalInRect:clipR];
    
//6、让剪切区域生效
    [clipPath addClip];
    
//7、将老图片画到剪切区域中
    [oldImage drawAtPoint:CGPointMake(borderW, borderW)];
    
//8、获取新的图片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    
//9、关闭图片上下文
    UIGraphicsEndImageContext();
    
    return newImage;
}

@end
